# coding =utf-8
# @Time :2023/8/25 6:00
# @Author : zcy
# @File : batch_create_word.py
# @SoftWare : PyCharm
import os
from openpyxl import load_workbook
from docx import Document


def create_word(template_path, data_path, target_path):
    # 模板路径 数据 对象
    try:
        if not os.path.exists(target_path):
            os.makedirs(target_path)
        if not os.path.exists(template_path):
            print("模板文件不存在！")
            return
        if not os.path.exists(data_path):
            print("资源文件不存在！")
            return
        # 加载excel文档，数据源
        sheet = load_workbook(data_path, data_only=True).active
        print("加载数据源")
        # 要替换的文本
        old_texts = [-1]
        for col_index in range(1, sheet.max_column + 1):
            old_texts.append(str(sheet.cell(row=1, column=col_index).value))

        # 遍历第一个sheet中的每一行
        for row_index in range(2, sheet.max_row + 1):
            print("生成一个word文件")
            word_file = Document(template_path)
            data_line_dic = {}
            for col_index in range(2, sheet.max_column + 1):
                old_text = old_texts[col_index]
                new_text = str(sheet.cell(row=row_index, column=col_index).value)
                data_line_dic[old_text] = new_text
            print("遍历文档中的段落")
            all_paragraphs = word_file.paragraphs
            for paragraph in all_paragraphs:
                for run in paragraph.runs:
                    for key, value in data_line_dic.items():
                        run.text = run.text.replace(key, value)
            print("遍历文档中的表格")
            all_tables = word_file.tables
            for table in all_tables:
                for row in table.rows:
                    for cell in row.cells:
                        for key, value in data_line_dic.items():
                            cell.text = cell.text.replace(key, value)
            file_name = str(sheet.cell(row=row_index, column=1).value)
            print("保存Word文档")
            word_file.save(target_path + '/' + f'/{file_name}.docx')
        print("程序结束")
    except Exception as e:
        print(e)


if __name__ == '__main__':
    create_word(
        r"D:\1mvp\record\excel2word\template.docx",
        r"D:\1mvp\record\excel2word\data.xlsx",
        r"D:\1mvp\record\excel2word\target"
    )
